package com.lb.activity.sys.service.impl;

import com.lb.activity.dynamicquery.DynamicQuery;
import com.lb.activity.sys.service.QuartzService;
import com.lb.activity.util.ResultUtil;
import com.lb.activity.vo.QuartzEntity;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;


/**
 * @author 001030
 */
@Service
public class QuartzServiceImpl implements QuartzService {


    @Autowired
    @Qualifier("Scheduler")
    private Scheduler scheduler;

    @Autowired
    private DynamicQuery dynamicQuery;

    /**
     * 添加任务
     * @param quartz
     * @return
     */
    @Override
    public ResultUtil addTask(QuartzEntity quartz) {
        try {
            //获取Scheduler实例、废弃、使用自动注入的scheduler、否则spring的service将无法注入
            //Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
            //如果是修改  展示旧的 任务
            if(quartz.getOldJobGroup()!=null){
                JobKey key = new JobKey(quartz.getOldJobName(),quartz.getOldJobGroup());
                scheduler.deleteJob(key);
            }
            Class cls = Class.forName(quartz.getJobClassName()) ;
            cls.newInstance();
            //构建job信息
            JobDetail job = JobBuilder.newJob(cls).withIdentity(quartz.getJobName(),
                    quartz.getJobGroup())
                    .withDescription(quartz.getDescription()).build();
            // 触发时间点
            CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(quartz.getCronExpression());
            Trigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger"+quartz.getJobName(), quartz.getJobGroup())
                    .startNow().withSchedule(cronScheduleBuilder).build();
            //交由Scheduler安排触发
            scheduler.scheduleJob(job, trigger);
        } catch (SchedulerException | ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
        return ResultUtil.ok(true);
    }

    /**
     * 任务列表
     * @param quartz
     * @return
     */
    @Override
    public ResultUtil listQuartzEntity(QuartzEntity quartz) {
        StringBuffer nativeSql = new StringBuffer();
        nativeSql.append("SELECT job.JOB_NAME as jobName,job.JOB_GROUP as jobGroup,job.DESCRIPTION as description,job.JOB_CLASS_NAME as jobClassName,");
        nativeSql.append("cron.CRON_EXPRESSION as cronExpression,tri.TRIGGER_NAME as triggerName,tri.TRIGGER_STATE as triggerState,");
        nativeSql.append("job.JOB_NAME as oldJobName,job.JOB_GROUP as oldJobGroup ");
        nativeSql.append("FROM qrtz_job_details AS job LEFT JOIN qrtz_triggers AS tri ON job.JOB_NAME = tri.JOB_NAME ");
        nativeSql.append("LEFT JOIN qrtz_cron_triggers AS cron ON cron.TRIGGER_NAME = tri.TRIGGER_NAME ");
        nativeSql.append("WHERE tri.TRIGGER_TYPE = 'CRON'");
        Object[] params = new  Object[]{};
        //加入JobName搜索其他条件自行实现
        if(!StringUtils.isEmpty(quartz.getJobName())){
            nativeSql.append(" AND job.JOB_NAME = ?");
            params = new Object[]{quartz.getJobName()};
        }
        List<QuartzEntity> quartzEntities = dynamicQuery.nativeQueryListModel(QuartzEntity.class, nativeSql.toString(), params);
        return ResultUtil.build(0,"",10,quartzEntities);
    }

    /**
     * 开始任务
     * @param quartz
     * @return
     */
    @Override
    public ResultUtil trigger(QuartzEntity quartz) {
        try {
            JobKey key = new JobKey(quartz.getJobName(),quartz.getJobGroup());
            scheduler.triggerJob(key);
        } catch (SchedulerException e) {
            e.printStackTrace();
            return ResultUtil.build(400,"失败");
        }
        return ResultUtil.ok();
    }

    /**
     * 停止任务
     * @param quartz
     * @return
     */
    @Override
    public ResultUtil stop(QuartzEntity quartz) {
        try {
            JobKey key = new JobKey(quartz.getJobName(),quartz.getJobGroup());
            scheduler.pauseJob(key);
        } catch (SchedulerException e) {
            e.printStackTrace();
            return ResultUtil.build(400,"失败");
        }
        return ResultUtil.ok();
    }

    /**
     * 恢复任务
     * @param quartz
     * @return
     */
    @Override
    public ResultUtil resume(QuartzEntity quartz) {
        try {
            JobKey key = new JobKey(quartz.getJobName(),quartz.getJobGroup());
            scheduler.resumeJob(key);
        } catch (SchedulerException e) {
            e.printStackTrace();
            return ResultUtil.build(400,"失败");
        }
        return ResultUtil.ok();
    }

    /**
     * 删除任务
     * @param quartz
     * @return
     */
    @Override
    public ResultUtil removeTask(QuartzEntity quartz) {
        try {
            TriggerKey triggerKey = TriggerKey.triggerKey(quartz.getJobName(), quartz.getJobGroup());
            // 停止触发器
            scheduler.pauseTrigger(triggerKey);
            // 移除触发器
            scheduler.unscheduleJob(triggerKey);
            // 删除任务
            scheduler.deleteJob(JobKey.jobKey(quartz.getJobName(), quartz.getJobGroup()));
            System.out.println("removeJob:"+JobKey.jobKey(quartz.getJobName()));
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.build(400,"失败");
        }
        return ResultUtil.ok();
    }
}
